#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include "../lib/net.h"
#include "../lib/protocol.c"
#include "../lib/state.h"
#include "../lib/update.h"
#include "../lib/object.h"

int numPlayers;
int gameState;
int port;
Maze *m;

static void *
do_protocol_test(void *arg)
{
	Player *myPlayerPtr;
	
	pthread_detach(pthread_self());
	receive((int)arg, port, m, myPlayerPtr);
	close((int)arg);
	return NULL;
}

int
main(int argc, char **argv)
{
	int listenfd, connfd;
	pthread_t tid;
	pthread_t tid2;
	fd_set read_set;

	// check valid arguments
	if (argc != 2)
		printf("usage: server <port>\n");
	sscanf(argv[1], "%d", &port);

	// setup socket that server listens on (listenfd)
	if (!net_setup_listen_socket(&listenfd, &port)) {
		fprintf(stderr, "net_setup_listen_socket FAILED!\n");
		exit(-1);
	}

	/* Initialize the read set to null */
    //FD_ZERO(&read_set);

	printf("Server listening to port %d\n", port);
	
	

	if (listen(listenfd, LISTENQ) < 0) {
		fprintf(stderr, "Error: server listen failed (%d)\n", errno);
		exit(-1);
	}
	

	// load map into maze structure
	m = load( MAP_PATH );
	printf("numhome1 %i, m=%i", m->numHome1, m);
	// initialize teams
	player_init();
	object_init(m);
	
	
	// continuously block on accept, pass off execution to thread
	// client socket descriptor = connfd
	for (;;) {
	
		
		
		connfd = accept(listenfd, NULL, NULL);
		if (connfd < 0) {
			fprintf(stderr, "Error: server accept failed (%d)\n", errno);
		} else {
			if ( numPlayers == NUM_PLAYERS_TO_START ) {
	
				// stop accepting new connections

				close(connfd);
			}
		else
			pthread_create(&tid, NULL, &do_protocol_test, (void *)connfd);
			// push thread
			//pthread_create(&tid2, NULL, &do_push, (void *)connfd);
			/* Add file descriptor connfd to read_set */
            // FD_SET(connfd, &read_set);

		}	
	}
}
